<template>
  <div id="navmenu" class="container">

    <div class="center">

      <h3 class="title"><span />导航管理</h3>
      <div class="navcate">
        <ul class="leftNavcate">
          <li class="navtitle">幻灯片分类</li>
          <li
            v-for="item in cateList"
            :key="item.id"
            :class="activeId== item.id? 'activeitem':''"
          >
            <span class="navtitle" @click="changeCate(item.id)">{{ item.id }}-{{ item.title }}</span>
            <div class="icon">
              <i class="el-icon-delete" @click="deleCate(item)" />
              <i class="el-icon-edit" @click="editCate(item)" />
            </div>
          </li>
          <el-button
            type="primary"
            class="add four"
            size="small"
            icon="el-icon-plus"
            style="margin:10px 0 10px 20px"
            @click="addCate"
          >添加分类</el-button>
        </ul>
        <div class="rightmenu">
          <el-button
            type="primary"
            icon="el-icon-plus"
            class="addFmenu add four"
            size="small"
            @click="addSlide"
          >添加幻灯片</el-button>
          <BouncedDialog :title="addForm.id?'编辑':'添加'" :dialog-show.sync="dialogShow" :width="50" class="addMenu">
            <el-form ref="addForm" :model="addForm" :rules="rules" class="addForm" label-width="80px">
              <el-form-item label="标题" prop="title">
                <el-input v-model="addForm.title" />
              </el-form-item>
              <el-form-item label="副标题" prop="sub_title">
                <el-input v-model="addForm.sub_title" />
              </el-form-item>
              <el-form-item label="链接地址" prop="url">
                <el-input v-model="addForm.url" />
              </el-form-item>
              <el-form-item label="描述" prop="description">
                <el-input v-model="addForm.description" type="textarea" :autosize="{ minRows: 4, maxRows: 8}" />
              </el-form-item>
              <el-form-item label="排序">
                <el-input v-model="addForm.sort" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="addForm.status">
                  <el-option label="显示" :value="1" />
                  <el-option label="隐藏" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item size="small" label="图片:" prop="attachment">
                <div class="attachmentBtn">
                  <el-upload
                    :headers="myHeaders"
                    class="avatar-uploader"
                    :action="$store.getters.updateURL+'attachment/uploadAndSave'"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :data="{type:2}"
                  >
                    <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
                  </el-upload>
                  <el-button
                    size="small"
                    class="blue"
                    type="primary"
                    icon="el-icon-s-unfold"
                    @click="openList('image')"
                  >选择附件</el-button>
                </div>
                <div class="imgBox">
                  <img v-if="addForm.attachment" :src="imageUrl" class="attachmentImg">
                </div>
                <BouncedDialog title="选择附件" :append="true" :dialog-show.sync="dialogShow3" :width="70" class="attachment">
                  <el-table
                    v-loading="loading"
                    v-el-table-infinite-scroll="load"
                    :data="attachmentData"
                    border
                    :header-cell-style="{'text-align':'center','background-color':'#fff'}"
                    :cell-style="{'text-align':'center'}"
                  >
                    <el-table-column label="ID" prop="id" width="60px" />
                    <el-table-column label="预览">
                      <template slot-scope="scope">
                        <el-image
                          :src="scope.row.url"
                          alt=""
                          class="attachmentImg"
                          :preview-src-list="scope.row.list"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="文件名" prop="name" />
                    <el-table-column label="文件大小" prop="size" width="100px" />
                    <el-table-column label="Mime类型" prop="mime_type" width="100px" />
                    <el-table-column label="创建日期" prop="create_time" width="160px" />
                    <el-table-column label="操作" width="120px">
                      <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-check" @click="choose(scope.row)">选择</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </BouncedDialog>
              </el-form-item>
              <div class="btn">
                <el-button @click="dialogShow = false">取 消</el-button>
                <el-button type="primary" @click="submit()">确 定</el-button>
              </div>
            </el-form>
          </BouncedDialog>
          <el-table
            ref="refTable"
            :data="slideList"
            row-key="id"
            :header-cell-style="{'text-align':'center','background-color':'#f5f5f5'}"
            :cell-style="{'text-align':'center'}"
          >
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column label="标题" prop="title" show-overflow-tooltip />
            <el-table-column label="链接地址" prop="url" show-overflow-tooltip />
            <el-table-column label="图片" prop="attachment">
              <template slot-scope="scope">
                <el-image
                  :src="scope.row.attachment.url"
                  alt=""
                  class="slideImg"
                  :preview-src-list="scope.row.list"
                />
              </template>
            </el-table-column>
            <el-table-column label="副标题" prop="sub_title" show-overflow-tooltip />
            <el-table-column label="简介" prop="description" show-overflow-tooltip />
            <el-table-column label="状态" prop="status" width="140px">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="2"
                  active-text="正常"
                  inactive-text="禁用"
                  active-color="#f84311"
                  inactive-color="rgba(0,0,0,0.2)"
                  @change="changeStatus(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="排序" prop="sort" />
            <el-table-column label="操作" fixed="right" width="150px">
              <template slot-scope="scope">
                <el-button size="mini" class="edit" @click="edit(scope.row)">编辑</el-button>
                <el-button size="mini" class="dele" @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- <el-pagination
            :current-page="page.currentPage"
            :page-sizes="page.pageSizes"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            :hide-on-single-page="page.total<page.size?true:false"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /> -->
        </div>
      </div>
    </div>
    <BouncedDialog :title="addForm2.id?'编辑':'添加'" :dialog-show.sync="dialogShow2" :width="50" class="addMenu">
      <el-form ref="addForm2" :model="addForm2" :rules="rules2" class="addForm" label-width="80px">
        <el-form-item label="分类名称" prop="title">
          <el-input v-model="addForm2.title" />
        </el-form-item>
        <el-form-item label="分类简介">
          <el-input v-model="addForm2.description" type="textarea" :autosize="{ minRows: 4, maxRows: 8}" />
        </el-form-item>
        <div class="btn">
          <el-button @click="dialogShow2 = false">取 消</el-button>
          <el-button type="primary" @click="submit2()">确 定</el-button>
        </div>
      </el-form>
    </BouncedDialog>
  </div>
</template>

<script>
import slideApi from '@/api/slide'
import { getToken } from '@/utils/auth'
import attachmentApi from '@/api/system/attachment'

var token = 'Bearer ' + getToken()
export default {
  data() {
    return {
      attachmentLimit: 10,
      dialogShow3: false,
      attachmentData: [],
      imagelist: [],
      attachmentType: '',
      imageUrl: '',
      loading: true,
      cateList: '', // 幻灯片分类列表
      activeId: '',
      siteId: '',
      myHeaders: { Authorization: token },
      searchForm: {
        website_id: '',
        cate_id: ''
      },
      slideList: [], // 幻灯片列表
      addForm: {},
      rules: {
        title: [
          { required: 'true', message: '请输入幻灯片标题', trigger: 'blur' }
        ],
        attachment: [
          { required: 'true', message: '请选择图片', trigger: 'change' }
        ]
      },
      dialogShow: false,
      dialogShow2: false, // 导航分类弹窗
      addForm2: {}, // 导航表单
      rules2: {
        title: [
          { required: 'true', message: '请输入导航名称', trigger: 'blur' }
        ]
      },
      id: '', // 幻灯片id
      navid: '', // 导航id
      langList: [],
      lang: '',
      category_id: '',
      page: {
        total: 0,
        currentPage: 1,
        size: 10,
        pageSizes: [10, 20, 30, 40]
      } // 分页器
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 幻灯片分类列表
    getCateList() {
      slideApi.slideCateList().then(res => {
        if (res.code == 0) {
          this.cateList = res.data
          if (res.data.length > 0) {
            this.changeCate(res.data[0].id)
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    changeCate(id) {
    //   this.searchForm.cate_id = id
      this.activeId = id
      this.getSlideList()
    },
    // 新增分类
    addCate() {
      this.addForm2 = {
        title: '',
        id: '',
        description: ''
      }
      this.dialogShow2 = true
    },
    // 编辑分类
    editCate(row) {
      this.addForm2 = {
        title: row.title,
        id: row.id,
        description: row.description
      }

      this.dialogShow2 = true
    },
    // 删除分类
    deleCate(row) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const val = {
          id: row.id
        }
        slideApi.slideCateDelete(val).then(res => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.getCateList()
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 提交添加、修改分类
    submit2() {
      this.$refs.addForm2.validate((valid) => {
        if (valid) {
          if (!this.addForm2.id) {
            const val = {
              title: this.addForm2.title,
              description: this.addForm2.description
            //   website_id: this.searchForm.website_id,
            //   lang: this.lang
            }
            slideApi.slideCateSave(val).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow2 = false
                this.getCateList()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            const val = {
              id: this.addForm2.id,
              title: this.addForm2.title,
              description: this.addForm2.description
            }
            slideApi.slideCateUpdate(val).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow2 = false
                this.getCateList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          this.$message.error('请填写必要信息')
        }
      })
    },
    // 幻灯片列表
    getSlideList() {
      const val = {
        slide_cate_id: this.activeId
        // page: this.page.currentPage,
        // limit: this.page.size
      }
      slideApi.slideList(val).then(res => {
        if (res.code == 0) {
          this.slideList = res.data
          this.loading = false
          this.imagelist = []
          // 获取每张图片的地址
          for (var m = 0;m < this.slideList.length;m++) {
            this.imagelist.push(this.slideList[m].attachment.url)
          }
          // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
          for (var n = 0;n < this.slideList.length;n++) {
            var container = this.imagelist
            var frontArr = container.slice(0, n)
            var begindArr = container.slice(n, this.slideList.length)
            var list = begindArr.concat(frontArr)
            this.slideList[n].list = list
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    load() {
      this.attachmentLimit += 10
      this.getAttachmentList()
    },
    // 打开附件弹窗
    openList(val) {
      this.attachmentType = val
      this.dialogShow3 = true
      this.getAttachmentList(val)
    },
    // 附件列表
    getAttachmentList() {
      const val = {
        limit: this.attachmentLimit,
        page: 1,
        type: 2
      }
      attachmentApi.attachmentList(val).then(res => {
        if (res.code == 0) {
          this.attachmentData = res.data
          this.loading = false
          this.imagelist = []
          // 获取每张图片的地址
          for (var x = 0;x < this.attachmentData.length;x++) {
            this.imagelist.push(this.attachmentData[x].url)
          }
          // 根据图片顺序（index）更改每张图片绑定的list的图片顺序
          for (var i = 0;i < this.attachmentData.length;i++) {
            var container = this.imagelist
            var frontArr = container.slice(0, i)
            var begindArr = container.slice(i, this.attachmentData.length)
            var list = begindArr.concat(frontArr)
            this.attachmentData[i].list = list
          }
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 选择附件
    choose(row) {
      this.addForm.attachment = row.id
      this.imageUrl = row.url
      this.dialogShow3 = false
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.code == -200 || res.code == 0) {
        this.$forceUpdate()
        // this.addForm.image_url = res.data.url
        this.imageUrl = res.data.url
        this.addForm.attachment = res.data.id
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      //   if (!isJPG && !isPNG) {
      //     this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      //   }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      }
      return isLt2M
    },
    // 添加幻灯片
    addSlide() {
      this.addForm = {
        id: '',
        title: '',
        description: '',
        sub_title: '',
        url: '',
        attachment: '',
        status: 1,
        sort: 100,
        slide_cate_id: this.activeId
      }
      this.dialogShow = true
    },
    // 编辑幻灯片
    edit(row) {
      this.imageUrl = row.attachment.url
      this.addForm = {
        id: row.id,
        title: row.title,
        description: row.description,
        sub_title: row.sub_title,
        url: row.url,
        attachment: row.attachment.id,
        slide_cate_id: this.activeId,
        status: row.status,
        sort: row.sort
      }
      this.dialogShow = true
    },
    // 修改幻灯片状态
    changeStatus(row) {
      this.imageUrl = row.attachment.url
      this.addForm = {
        id: row.id,
        title: row.title,
        description: row.description,
        sub_title: row.sub_title,
        url: row.url,
        attachment: row.attachment.id,
        slide_cate_id: this.activeId,
        status: row.status,
        sort: row.sort
      }
      slideApi.slideUpdate({ ...this.addForm }).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    // 提交添加、修改幻灯片
    submit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (!this.addForm.id) {
            slideApi.slideSave({ ...this.addForm }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.getSlideList()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            slideApi.slideUpdate({ ...this.addForm }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.getSlideList()
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          this.$message.error('请填写必要信息')
        }
      })
    },
    // 删除幻灯片
    del(row) {
      this.$confirm('此操作将永久删除该幻灯片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const val = {
          id: row.id,
          slide_cate_id: row.slide_cate_id
        }
        slideApi.slideDelete(val).then(res => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.getSlideList()
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  },
  // 分页规格改变
  handleSizeChange(val) {
    this.page.size = val
    this.page.currentPage = 1
    this.getSlideList()
  },
  // 分页点击
  handleCurrentChange(val) {
    this.page.currentPage = val
    this.getSlideList()
  }
}
</script>
<style lang="scss">
.attachment .el-dialog{
  .el-dialog__body{
    height: 600px;
  }
  .el-table{
    .attachmentImg{
      width: 60px;
      height: 60px;
    }
  }
  .el-button--primary{
    background-color:#f84311;
    border-color: #f84311;
    border-radius: 20px;
  }
}
#navmenu{
  .el-tabs__header{
    margin-bottom:0 ;
  }
  .tabs.el-tabs--card>.el-tabs__header .el-tabs__item{
  background-color: #eee;
  border: none;

}
.tabs.el-tabs--card>.el-tabs__header .el-tabs__nav{
  border-radius: 0;
}
.tabs.el-tabs--card>.el-tabs__header .el-tabs__item.is-active{
  background-color: #fff;
}
  .addMenu{
    .el-select{
      width: 100%;
    }
    .el-input.type, .el-select.type{
      width: 200px;
      margin-right: 30px;
    }
  }
  .el-cascader-panel .el-radio{
      width: 100%;
      height: 100%;
      z-index: 10;
      position: absolute;
      top: 10px;
      right: 10px;
  }
  .el-cascader-panel .el-radio__input{
      visibility: hidden;
  }
  .el-cascader-panel .el-cascader-node__postfix {
      top: 10px;
  }

}
</style>
<style scoped lang='scss'>
.slideImg{
    width: 50px;
}
.center{
  background-color: #fff;
  padding-bottom: 20px;
  border: solid 1px #eee;
  border-top: none;
  h3.title{
    margin-left: 20px;
  }
  .navcate{
    // border-top: solid 1px #eee;
    display: flex;
    justify-content: left;
  }
}
.leftNavcate{
    list-style: none;
    margin-top: 20px;
    li.navtitle{
      font-size: 15px;
      font-weight: bold;
    }
    li{
      width: 220px;
      padding: 0 20px;
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .navtitle{
        cursor: pointer;
        width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .icon{
        display: none;
        i{
          cursor: pointer;
        }
        .el-icon-delete{
          margin-right: 10px;
        }
      }

    }
    .activeitem .icon{
        display: block;
      }
    // hover的样式
    li:hover{
      color: #f84311 ;
      background-color: #f4f8fc;
      .icon{
        display: block;
      }
    }
    //选中的样式
    li.activeitem{
      color: #f84311 ;
      background-color: #f4f8fc;
    }
}
.rightmenu{
  -webkit-box-flex: 3;
  box-flex:3;
  padding-top: 20px;
  padding-left: 15px;
  border-left: solid 1px #eee;
  width: calc(100% - 220px);
  .addFmenu{
    margin-bottom: 20px;
  }
}
.status{
  padding: 5px 10px;
  color: #fff;
  border-radius: 5px;
}
.status.show{
  background-color: #0bc40f;
}
.status.hide{
  background-color: #df9513;
}
.addCmenu{
  color: #fff;
  background-color: #fe872b;
  border-color: #edeef3;
  border-radius: 16px;
}
.editor{
  color: #fff;
  background-color: #31b0d5;
  border-color: #2aabd2;
}
.dele{
  color: #fff;
  background-color: #ed5554;
  border-color: #ed5554;
}
</style>
